package com.gopay.bis.pab.ebank.operation;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateException;
import java.security.spec.InvalidKeySpecException;
import java.util.Hashtable;

import sun.misc.BASE64Decoder;

public class VerifySignUtil {
	/* ֤���ļ��е�Key�� */
	private Hashtable keyEntry = new Hashtable();
	/* ֤���ļ��е�CA֤���� */
	private Hashtable certificateEntry = new Hashtable();

	private InputStream inputSteam;

	public static void main(String[] args) throws Exception {
		String signData = "7478b9eef08f6fdaba044344be2a5a863090265604b792f25bfdd802652f526ae0328311da2e49c29961a89577a28ebc91dbe64839a6a1a224c5c0abf62b2ed19873f76c1277e4fa38903752037992bebb151e952f494bdce1c41e2dd45cf2a1b930bdca4e25239da75708e5c267cd72e2213428391aeeca33ccffd1a0a96319";
		String orgData = "status=0|errDesc=|paydate=20170831|paytimestamp=1504170077042|seqno=8720801708312159990432|payAcc=11012296147102|payerAccName=国付宝信息科技有限公司|masterid=1000089745|orderid=2017083102611155|currency=RMB|amount=0.01|timestamp=20170831163224|validtime=0|remark=gopay|merchantName=guofubao";

		VerifySignUtil test = new VerifySignUtil();
		KeyStore keyStore = test.KeyStoreUtil("/Users/lynn/desktop/merchant_b2b.jks", "changeit");
		boolean abc = test.verifyData(keyStore.getCertificate("sdb").getPublicKey(), signData, orgData, "MD5withRSA");
		System.out.println(abc);

	}

	public boolean verifyData(PublicKey publicKey, String signData, String orgData, String alg) {

		try {
			if (publicKey == null || signData == null || orgData == null || alg == null) {
				System.out.println("KeyStoreUtil.verifyData(): publicKey or signData or orgData or alg is null");
				return false;
			}

			Signature dsa = Signature.getInstance(alg);

			dsa.initVerify(publicKey);

			dsa.update(orgData.getBytes("GBK"));

			byte sig[] = hexToByte(signData);
			return dsa.verify(sig);

		} catch (Exception e) {

			return false;
		}

	}

	public static byte[] hexToByte(String inbuf) {

		int i;
		int len = inbuf.length() / 2;
		byte outbuf[] = new byte[len];

		for (i = 0; i < len; i++) {
			String tmpbuf = inbuf.substring(i * 2, i * 2 + 2);

			outbuf[i] = (byte) Integer.parseInt(tmpbuf, 16);

		}

		return outbuf;
	}

	public static PublicKey getPubKey() {
		PublicKey publicKey = null;
		try {
			// ��Կ ����
			// String pubKey =
			// "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbwbLSAtuRp686uRUlN/EXxEyMB0BLN2EWBQLu8Zryl5ML80wi8i3JpYrZ0UWomycUpPhsyJ0lRC1i/oGmHGZ0ltXF3z/y6dc+mdE8WWu32K2fMLyEkq76x9ABJT1MtqAeu4C5zn13/FAC0hQtfYi72Aydz9FzF90m7fVYcPkVKwIDAQAB";
			// ��Կ����
			String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8BLDHKFUJ56PmqT/OZ8im77NfqfPAIm6HxXSNpUGc2MUv+bDgvK7yKNVZ2AS5S2dMyOkhS83GiCQodoeGCiR4bCKjxe5kUeCcRRIg/cIWSk3DdnIUPkH4rIRDIxY3HJg39LsWvptdk3yVIYad+ZOVRpNAUkFCS0ru53YECcNnqQIDAQAB";
			java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(pubKey));
			// RSA�ԳƼ����㷨
			java.security.KeyFactory keyFactory;
			keyFactory = java.security.KeyFactory.getInstance("RSA");
			// ȡ��Կ�׶���
			publicKey = keyFactory.generatePublic(bobPubKeySpec);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return publicKey;
	}

	public KeyStore KeyStoreUtil(String keyName, String storePassword) throws FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
		KeyStore keyStore;
		if (keyName == null) {
			keyName = System.getProperty("JAVA_HOME") + "/jre/lib/security/cacerts";
		}

		try {
			inputSteam = new FileInputStream(keyName);
		} catch (FileNotFoundException e) {
			System.out.println("File Not Found." + e);
			throw e;
		}

		char[] pass = storePassword == null ? null : storePassword.toCharArray();

		try {

			keyStore = KeyStore.getInstance("JKS");
			keyStore.load(inputSteam, pass);

		} catch (KeyStoreException e1) {
			System.out.println("KeyStoreUtil error." + e1);
			throw e1;
		} catch (NoSuchAlgorithmException e2) {
			System.out.println("KeyStoreUtil error." + e2);
			throw e2;
		}

		return keyStore;

	}

	public static String Base64Decode(String base64, String code) throws Exception {
		// if(StrUtil.isEmpty(base64)){
		// return null;
		// }
		byte[] bytes = null;
		try {
			bytes = new BASE64Decoder().decodeBuffer(base64);
		} catch (IOException e) {

		}

		String param = "";
		try {
			param = new String(bytes, code);
		} catch (UnsupportedEncodingException e) {

		}
		return param;
	}
}
